import React, {PropTypes} from 'react';
import {connect} from 'react-redux'

import {Divider, Dropdown, Button, Menu, Modal, message} from "antd";
import {deepFullCopy, messages, queryCurrencyPrecision} from "share/common";
import loadingImg from "images/expense-report/loading.png";
import auditingImg from "images/expense-report/auditing.png";
import ExpenseCheckResult from "containers/expense-report/components/expense-check-result";
import Designate from "components/template/designate";
import expenseReportService from "containers/expense-report/expense-report.service";
import requestService from "containers/request/request.service";
import errorMessage from "share/errorMessage";
import expenseReportFunction from "containers/expense-report/expense-report.function";
import corporatePaymentReportService from 'containers/corporate-payment-report/corporate-payment-report.service';

const { corporatePaymentReportValidator, handleSubmitError } = expenseReportFunction;

class SubmitAndCheckResult extends React.Component {

  state = {
    loading: false,
    submitting: false,
    showChecking: false,
    checkingText: '',
    directSubmitting: false,
    nodeList: [],
    checkResult: []
  };

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  static contextTypes = {
    info: PropTypes.object,
    form: PropTypes.object,
    invoiceEnabled: PropTypes.bool,
    approvalHistory: PropTypes.array,
    isAuditInApproveStatus: PropTypes.bool,
    isWaitForAudit: PropTypes.bool,
    entry: PropTypes.string,
    showApproveBottom: PropTypes.bool
  };

  handleSubmit = () => {
    let { info, approvalHistory } = this.context;
    const { expenseReportInvoices, payInfoList } = this.props;
    const { loading } = this.state;
    if (loading) {
      message.warning(messages('expense-1.key328')/*数据加载中，请稍后...*/);
    } else if (corporatePaymentReportValidator(expenseReportInvoices, payInfoList)) {

      info.expenseReportInvoices = expenseReportInvoices;
      this.setState({ submitting: true });
      let addSign = [];
      if (info.countersignApproverNames) {
        info.countersignApproverNames.map(item => {
          addSign.push(item.fullName);
        });
      }
      let repeat = [];
      approvalHistory.map(item => {
        item.operation === 2001 &&
        item.operator &&
        ~addSign.indexOf(item.operator.fullName) &&
        (repeat.push(item.operator.fullName));
      });
      let names = [...new Set(repeat)];
      if (names.length) {
        Modal.confirm({
          title: `${names.join('、')} ${messages('expense-1.key329')/*已经审批通过，是否继续*/}？`,
          onOk: this.checkBudget,
          onCancel: () => this.setState({ submitting: false })
        });
      } else {
        this.checkBudget();
      }
    }


  };

  //预算检查
  checkBudget = () => {
    let { info } = this.context;
    expenseReportService.checkAsync(info.expenseReportOID).then(res => {
      if(res.data){
        Modal.confirm({
          content: messages('expense-1.key331')/*忽略提交过程中的警告信息，直接提交？*/,
          onOk: () => this.handleLastSubmit(true),
          okText: messages('common.yes')/*是*/,
          cancelText: messages('common.no')/*否*/,
          onCancel: () => this.handleLastSubmit(false)
        })
      } else {
        this.handleDesignate().then();
      }
    }).catch(e => {
      this.setState({ submitting: false });
      this.props.getInfo(info, false);
      //this.getExpenseList();
      message.error(e.response.data.message);
    });
  };

  handleDesignate = async () => {
    const { form, info } = this.context;
    try {
      let isDesignate = await requestService.getIsDesignate({
        formOID: form.formOID,
        applicantOID: info.applicantOID
      });
      if (isDesignate.data && isDesignate.data.showDesignate) {
        const ret = await requestService.getNodeList({ entityOID: info.expenseReportOID, entityType: 1002 });
        const nodeList = ret.data.approvalDesignateNodeList || [];
        if (nodeList.length) {
          this.setState({ designateVisible: true, nodeList });
        } else {
          this.handleLastSubmit();
        }
      } else {
        this.handleLastSubmit();
      }
    } catch (e) {
      this.setState({ submitting: false, showChecking: false, checkingText: '' });
      errorMessage(e.response);
    }
  };

  handleLastSubmit = (ignoreWarnCheck = null) => {
    let { info } = this.context;
    typeof ignoreWarnCheck === 'boolean' && (info.ignoreWarnCheck = ignoreWarnCheck);
    info.isDateCombinedUTC = false;
    info.corporateFlag = true;
    this.setState({showChecking: true, checkingText: messages('common.submitting')/*正在提交...*/});  //正在提交
    corporatePaymentReportService.submitOrCheckBudget(info).then(res => {
      this.setState({showChecking: false, checkingText: ''}, () => {
        // true代表可提交， false时提示错误信息
        if (!res.data.checkResultList || res.data.checkResultList.length === 0) {
          this.setState({submitting: false, showChecking: false, checkingText: ''});
          message.success(messages('common.operate.success')/*操作成功*/);  //操作成功
          this.props.goBack(true);
        } else {
          let budgetError = false;
          res.data.checkResultList.map(item => {
            budgetError = budgetError || item.type === 1;
          });
          this.setState({
            checkResult: res.data.checkResultList,
            showChecking: false,
            checkingText: '',
            showCheckResult: true,
            submitting: !budgetError
          })
        }
      });
    }).catch((err) => {
      this.setState({ showChecking: false, submitting: false });
      handleSubmitError(err);
    })
  };

  //预算检查时忽略预警直接保存
  confirmSubmit = () => {
    let {info} = this.context;
    info.ignoreBudgetWarningFlag = true;
    info.isDateCombinedUTC = false;
    this.setState({directSubmitting: true});
    expenseReportService.submitOrCheckBudget(info).then(res => {
      let budgetError = false;
      res.data.checkResultList && res.data.checkResultList.map(item => {
        budgetError = budgetError || item.type === 1;
      });
      if (budgetError) {
        this.setState({
          checkResult: res.data.checkResultList,
          showChecking: false,
          checkingText: '',
          showCheckResult: true,
          submitting: false
        })
      }
      else {
        this.setState({directSubmitting: false, showChecking: false,});
        message.success(messages('common.operate.success')/*操作成功*/);  //操作成功
        this.props.goBack(true);
      }
    }).catch((err) => {
      info.ignoreBudgetWarningFlag = false;
      this.setState({ showChecking: false, directSubmitting: false, showCheckResult: false, submitting: false });
      handleSubmitError(err);
    })
  };

  //预算检查后取消继续提交
  afterBudgetCheckCancel = () => {
    let { info } = this.context;
    this.setState({
      showCheckResult: false,
      submitting: false
    }, () => {
      let isNeedRefresh = false;
      this.state.checkResult.map(item => {
        if (item.externalPropertyName && String(item.externalPropertyName) !== '9002')
          isNeedRefresh = true
      });
      if (isNeedRefresh) {
        this.props.getInfo(info, true);
      }
    })
  };

  // isSuccess 是否是成功的指派选人
  handleCloseDesignate = (isSuccess) => {
    this.setState({ designateVisible: false });
    if (isSuccess) {
      this.handleLastSubmit();
    } else {
      this.cancelSubmit();
    }
  };

  render() {
    const { showChecking, checkingText, showCheckResult, checkResult, directSubmitting,
      designateVisible, nodeList } = this.state;
    const {} = this.props;
    const { info } = this.context;
    return <div>
      <Modal
        visible={showChecking}
        maskClosable={false}
        footer={null}
        closable={false}
        wrapClassName="expense-report-checking"
      >
        <img src={loadingImg} className="checking-img"/>
        <img src={auditingImg} className="checking-img-content"/>
        <div className="checking-divide"/>
        <div className="checking-title">{checkingText}</div>
        <div className="checking-content">{messages('common.waiting')/*请稍等...*/}</div>
      </Modal>

      {/*报销单提交时检查结果*/}
      <ExpenseCheckResult
        visible={showCheckResult}
        checkResult={checkResult}
        submitLoading={directSubmitting}
        confirmSubmit={this.confirmSubmit}
        confirmText={messages('expense-1.key344')/*继续提交*/}
        onCancel={this.afterBudgetCheckCancel}
      />
      <Designate
        entity={{
          entityType: 1002,
          entityOID: info.expenseReportOID
        }}
        modalVisible={designateVisible}
        nodeList={nodeList}
        onClose={this.handleCloseDesignate}
      />
    </div>
  }
}

SubmitAndCheckResult.propsType = {

};

SubmitAndCheckResult.defaultProps = {

};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
    user: state.login.user,
    authPolicyAll: state.main.authPolicyAll,
    options: state.login.options,
    profile: state.login.profile,
  }
}

export default connect(mapStateToProps)(SubmitAndCheckResult)
